#version 150 core

uniform sampler2D diffuseTex;
uniform sampler2D depthTex;
//blur values
uniform int    isBlur;
uniform float  blurRadius;

//fog values
uniform float  fDensity;
uniform vec4   vFogColor;
uniform int    isFog;

in Vertex{
	vec2 texCoord;
} IN;

out vec4 gl_FragColor;

float LinearDepth(float zoverw){

	float f = 30000.0;
	float n = 200;
	float z = (2 * n) / (f + n - zoverw * (f - n));
	return z;
}

void main(void)
{
	if (isBlur == 1){
		vec2  radial_size = vec2(1.0 / 800.0, 1.0 / 600.0);
		vec2  radial_origin = vec2(0.5, 0.4);

		vec2 TexCoord = IN.texCoord;
		vec4 SumColor = vec4(0.0, 0.0, 0.0, 0.0);
		TexCoord += (radial_size * 0.5 - radial_origin);
		int nSamples = 20;
		for (int i = 0; i < nSamples; i++)
		{
			float scale = 1.0 - blurRadius * (float(i) / float(nSamples - 1));
			SumColor += texture2D(diffuseTex, TexCoord * scale + radial_origin);
		}
		gl_FragColor = SumColor / nSamples;
		//Add fog
		if (isFog == 1)
		{
			vec2  texCoord = IN.texCoord;
			float d = LinearDepth(texture2D(depthTex, texCoord).x);

			//vec4 outputColor = texture2D(diffuseTex, texCoord);

			float fResult = exp(-pow(fDensity * d, 2.0));
			fResult = 1.0 - clamp(fResult, 0.0, 1.0);
			//gl_FragColor = mix(outputColor, vFogColor, fResult);
			gl_FragColor = mix(gl_FragColor, vFogColor, fResult);
			//gl_FragColor = vec4(d, d, d, 1);
		}
	}
	//	 Add fog
	//else if (isFog == 1){
	//	vec2  texCoord = IN.texCoord;
	//	float d = LinearDepth(texture2D(depthTex, texCoord).x);

	//	vec4 outputColor = texture2D(diffuseTex, texCoord);

	//	float fResult = exp(-pow(fDensity * d, 2.0));
	//	fResult = 1.0 - clamp(fResult, 0.0, 1.0);
	//	gl_FragColor = mix(outputColor, vFogColor, fResult);
	//	// gl_FragColor = texture2D(depthTex, texCoord)
	//}
	else
	{
		gl_FragColor = texture2D(diffuseTex, IN.texCoord);
	}

}










/*
vec2  texCoord = IN.texCoord;
float zOverW = texture(depthTex, texCoord).r;
vec4  H = vec4(texCoord.x * 2 - 1, (1 - texCoord.y ) * 2 - 1, zOverW, 1);
vec4  D = IN.inverseProjView * H;
vec4  worldPos = D/D.w;

vec4  currentPos = H;
vec4  previousPos = IN.preProjView * worldPos;
previousPos/= previousPos.w;

vec2  velocity = vec2(currentPos - previousPos)/2.f;

vec4  color= texture2D(diffuseTex, texCoord);
texCoord -= velocity;

int nSamples = 10;

for(int i = 1; i < nSamples; ++i, texCoord -= velocity)
{
vec4 currentColor = texture2D(diffuseTex,texCoord);
color += currentColor;
}
gl_FragColor = color / nSamples;
*/